//
//  M4PagoDetailViewController.swift
//  M4
//
//  Created by YuChuang on 2024/8/28.
//

import UIKit

class M4PagoDetailViewController: M4BaseViewController {
    
    var M4PagoId: Int = 0
    
    private var M4PagoDetailModel: M4LoanResultModel?
    
    private var M4ChannelModel: [M4ChannelDataModel] = []
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        M4PagoDetailNet()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        M4NavTitle(M4Title: "Pago")
        let bgview = UIView()
        bgview.backgroundColor = COLOR_00479D
        view.addSubview(bgview)
        bgview.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(M4NavigationFullHeight()-0.5)
            make.left.right.equalToSuperview()
            make.height.equalTo(180)
        }
        view.addSubview(M4TableView)
        M4TableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(M4NavigationFullHeight())
            make.bottom.equalToSuperview().offset(-M4SafeDistanceBottom())
        }
        M4addRefreshToTaleView { [weak self] in
            self?.M4PagoDetailNet()
        }
    }
    
    override func M4BackClick(sender: UIButton) {
        let alert = UINib(nibName: "M4InfosBackAlertView", bundle: nil).instantiate(withOwner: self).last as! M4InfosBackAlertView
        alert.M4BackAlertUI(title: "Se generará intereses de penalización al superar la fecha de vencimiento.Por favor, pague lo antes posible.", containuaText: "Reembolso inmediato", quitText: "Lo pensaré")
        alert.M4QuitBlock = {
            self.navigationController?.popViewController(animated: true)
        }
        alert.M4AlertViewShow()
        sender.M4EventUnavailable = false
        
        self.uploadData()
    }
    
    override func M4DataRefresh() {
        M4PagoDetailNet()
    }
    
    override func M4CellAction(_ action: M4IDAction) {
        let type = M4PagoAction(rawValue: action.M4ActionType)
        if type == .M4ToProrrogaPageAction {
            let data = action.M4ActionData as? M4LoanOrderListModel
            let page = M4ProrrogaDetiailViewController()
            page.M4ProrrogaData = data?.XPvy?[0]
            page.productName = data?.LcMnJMQqO ?? ""
            page.M4MainLoanId = data?.Jajlc ?? 0
            page.M4ProductItemCode = data?.NbN ?? ""
            self.navigationController?.pushViewController(page, animated: true)
        }
        else if type == .M4ChannelAction {
            let code = action.M4ActionData as? String ?? ""
            M4RepayCodeNet(channelCode: code)
        }
    }
    
    private func M4PagoDetailDataSource() {
        M4TableSources.removeAll()
        M4TableSources.append(M4TableViewCellData("M4PagoDetailCell", XIB: true, M4PagoDetailModel?.QKDLhYTHobF?[0] ?? M4LoanOrderListModel()))
        M4TableSources.append(M4TableViewCellData("M4PagoChannelCell", XIB: true, M4ChannelModel))
        M4TableView.reloadData()
    }
    
    private func M4PagoDetailNet() {
        let loading = M4LoadingAlertView()
        loading.M4LoadingAlertShow()
        let para: [String : Any] = ["YjWGJmF": "ESP", "DnVc": M4UserDataManager.m4UserShare.M4Itemcode, "IxENPg": M4UserDataManager.m4UserShare.M4Token, "IQAfZSgHc":M4PagoId]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4OrderDetail, .post, params: para), false) { model in
            self.M4endRefresh()
            if model.code == 1 {
                self.asdqwrA = 1
                let data = model.data as? [String : Any]
                self.M4PagoDetailModel = data?.kj.model(M4LoanResultModel.self)
                self.M4ChannelNet(alert: loading, proCode: self.M4PagoDetailModel?.QKDLhYTHobF?[0].NbN ?? "")
                self.fASDW = self.M4PagoDetailModel?.QKDLhYTHobF?.first?.LcMnJMQqO ?? ""
            }
            else {
                self.asdqwrA = 0
                loading.M4AlertViewHidden()
                self.view.makeToast(model.message, position: .center)
                self.navigationController?.popViewController(animated: true)
            }
        }
        
    }
    
    private func M4ChannelNet(alert: M4LoadingAlertView, proCode: String) {
        let para: [String : Any] = ["McTPi": "ESP", "QqEuBTPo": M4UserDataManager.m4UserShare.M4Itemcode, "ABSPKCGrmp": M4UserDataManager.m4UserShare.M4Token, "Nsm":proCode]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4channel, .post, params: para), false) { model in
            alert.M4AlertViewHidden()
            if model.code == 1 {
                let data = model.data as? [[String : Any]]
                self.M4ChannelModel = data?.kj.modelArray(M4ChannelDataModel.self) ?? []
            }
            else {
                self.view.makeToast(model.message, position: .center)
            }
            self.M4PagoDetailDataSource()
            if self.M4PagoDetailModel?.QKDLhYTHobF?[0].LlCrBfHzOES == 1 {
                self.navigationController?.popViewController(animated: true)
            }
        }
    }
    
    private func M4RepayCodeNet(channelCode: String) {
        SDA = Int(Date().timeIntervalSince1970 * 1000)
        let para: [String : Any] = ["Vhd": "ESP", "BGONVys": M4UserDataManager.m4UserShare.M4Itemcode, "ZpUlgE": M4UserDataManager.m4UserShare.M4Token, "GVhChbrK":M4PagoDetailModel?.QKDLhYTHobF?[0].Jajlc ?? 0, "HemM": channelCode, "DCDf": M4PagoDetailModel?.QKDLhYTHobF?[0].NbN ?? "", "ZUfo": 1, "EyhGSCZAn": M4PagoDetailModel?.QKDLhYTHobF?[0].XPvy?[0].LpjOv ?? 0]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4repayCode, .post, params: para)) { model in
            if model.code == 1 {
                self.GGa = 1
                let data = model.data as? [String : Any]
                let link = data?["tJslhw"] as? String ?? ""
                if link != "" {
                    let htmlVC = M4HtmlWebViewController()
                    htmlVC.M4WebTitle = "Pago"
                    htmlVC.M4WebUrl = link
                    self.navigationController?.pushViewController(htmlVC, animated: true)
                }
            }
            else {
                self.GGa = 0
                self.view.makeToast(model.message, position: .center)
            }
            
            self.uploadData()
        }
    }
    
    var SDA = 0, fASDW = "", GGa = 0, asdqwrA  = 0
    func uploadData() {
        let params: [[String:Any]] = [
            [
                "adga" : 10001,
                "sdqw" : inTime,
                "hgjyj" : Int(Date().timeIntervalSince1970 * 1000) ,
                "SDA" : SDA,
                "fASDW" : fASDW,
                "GGa" : GGa,
                "asdqwrA" : asdqwrA
            ]
        ]
        M4HiddenPointDataManager.M4UploadHiddenPoint(type: .PayDetail, paramsKey: "asde", params: params, complete: nil)
    }

}
